package com.wyw.elasticsearch.learning.controller;

import com.wyw.elasticsearch.learning.common.Tes12345;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Title
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2024/4/25 17:25
 * Update History:
 * Author        Time            Content
 */
@RestController
@RequestMapping("esdsl")
@Slf4j
@RequiredArgsConstructor
public class EsDSLTestController {

    private final ElasticsearchRestTemplate esTemplate;
    private final RestHighLevelClient client; // 初始化您的RestHighLevelClient实例

    @PostMapping("saveTestData12345")
    public Object saveTestData12345(@RequestParam String userId,
                                    @RequestParam String aId,
                                    @RequestParam String name,
                                    @RequestParam Integer age,
                                    @RequestParam String birthday,
                                    @RequestParam String refreshTime,
                                    @RequestParam String username) {
        Tes12345 data = new Tes12345();
        data.setUserId(userId);
        data.setAId(aId);
        data.setUsername(username);
        data.setName(name);
        data.setAge(age);
        data.setBirthday(birthday);
        data.setRefreshTime(refreshTime);

        IndexQuery iq = new IndexQueryBuilder().withObject(data).build();

        IndexCoordinates ic = IndexCoordinates.of("tes12345");

        String saveResult = esTemplate.index(iq, ic);
        log.info("新增返回:[{}]", saveResult);
        return "OK";
    }

    @GetMapping("testQuery12345")
    public Object testQuery12345() throws IOException {

        // 1. 创建SearchRequest对象
        SearchRequest searchRequest = new SearchRequest("tes12345");

        // 2. 构建搜索源（DSL查询） 创建SearchSourceBuilder实例
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 创建一个MatchQueryBuilder，设置name字段、查询值和operator为and
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "测试2");
        matchQuery.operator(Operator.AND);

        // 将构建好的match查询设置到SearchSourceBuilder中
        searchSourceBuilder.query(matchQuery);

        // 添加排序条件
        searchSourceBuilder.sort("refreshTime", SortOrder.DESC);

        // 设置分页
        searchSourceBuilder.size(10); // 取前10条记录
        searchSourceBuilder.from(0); // 从第一条开始

        // 设置返回的_source字段
        searchSourceBuilder.fetchSource(new String[]{"name", "username", "aId", "birthday", "refreshTime"}, null); // 只返回指定字段

        searchRequest.source(searchSourceBuilder);

        // 3. 执行搜索请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // 4. 处理搜索结果
        long totalHits = searchResponse.getHits().getTotalHits().value;
        log.info("总数目：[{}]", totalHits);

        for (org.elasticsearch.search.SearchHit hit : searchResponse.getHits().getHits()) {

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            // 处理或打印source中的字段值
            log.info("name:{}", sourceAsMap.get("name"));
            log.info("userName:{}", sourceAsMap.get("username"));
            log.info("aId:{}", sourceAsMap.get("aId"));
            log.info("birthday:{}", sourceAsMap.get("birthday"));
            log.info("refreshTime:{}", sourceAsMap.get("refreshTime"));
        }

        return "OK";
    }

}
